package com.boomsecret.js;

import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;

/**
 * Created by wangjinliang on 2018/5/9.
 */
public class JSDemo {
    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Bindings bindings = engine.createBindings();
        bindings.put("name", "Tom");
        engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        engine.eval(new FileReader(getClassPath()));
        if (engine instanceof Invocable) {
            Invocable in = (Invocable) engine;
            String result = (String) in.invokeFunction("test", "Hello");
            System.out.println(result);
        }
    }

    private static String getClassPath() {
        return "D:\\github\\JavaDemo\\src\\main\\java\\test.js";
    }
}
